package cn.snmp.mutual.uk.stack;

import java.io.*;

public class AsnInteger extends AsnObject {
    private static final String version_id = "@(#)$Id: AsnInteger.java,v 3.14 2008/05/27 15:40:14 birgita Exp $ Copyright Westhawk Ltd";
    protected int value;

    public AsnInteger(final int v) {
        this.value = v;
        this.type = 2;
    }

    public AsnInteger(final InputStream in, final int len) throws IOException {
        final byte[] data = new byte[len];
        if (len != in.read(data, 0, len)) {
            throw new IOException("AsnInteger(): Not enough data");
        }
        final int val = this.bytesToInteger(data);
        this.value = val;
    }

    public int getValue() {
        return this.value;
    }

    @Override
    public String toString() {
        return String.valueOf(this.value);
    }

    @Override
    int size() {
        int empty = 0;
        int sign = 0;
        if (this.value < 0) {
            empty = 255;
            sign = 128;
        }
        int count;
        for (count = 24; count > 0 && (this.value >> count & 0xFF) == empty; count -= 8) {
        }
        if ((this.value >> count & 0x80) != sign) {
            count += 8;
        }
        return (count >> 3) + 1;
    }

    @Override
    void write(final OutputStream out, final int pos) throws IOException {
        int empty = 0;
        int sign = 0;
        if (this.value < 0) {
            empty = 255;
            sign = 128;
        }
        int count;
        for (count = 24; count > 0 && (this.value >> count & 0xFF) == empty; count -= 8) {
        }
        if ((this.value >> count & 0x80) != sign) {
            count += 8;
        }
        this.AsnBuildHeader(out, (byte) 2, (count >> 3) + 1);
        if (AsnInteger.debug > 10) {
            System.out.println("\tAsnInteger(): value = " + this.value + ", pos = " + pos);
        }
        while (count >= 0) {
            out.write((byte) (this.value >> count & 0xFF));
            count -= 8;
        }
    }

    protected int bytesToInteger(final byte[] data) throws IOException {
        final DataInputStream dis = new DataInputStream(new ByteArrayInputStream(data));
        int val = 0;
        final int size = data.length;
        val = dis.readByte();
        for (int n = 1; n < size; ++n) {
            val = (val << 8) + dis.readUnsignedByte();
        }
        return val;
    }

    @Override
    public boolean equals(final Object obj) {
        return obj instanceof AsnInteger && this.value == ((AsnInteger) obj).value;
    }

    @Override
    public int hashCode() {
        return this.value;
    }
}
